#include "s_uart_msg.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "h_cc2640r2f_define.h"
#include "h_cc2640r2f_uart.h"

#include "s_opendoor_ctl.h"

typedef enum
{
	unknown = 0,
	ble_remotecontroller
}s_lock_msg_type;

#define S_MSG_RM_HEAD_1            		'R'
#define S_MSG_RM_HEAD_2            		'C'

#define S_MSG_HEAD_LENGTH           	2

/* Ask ble device connection and getting random data */
#define S_MSG_CMD_BLE_CNRANDOM_HEAD_1	'C'
#define S_MSG_CMD_BLE_CNRANDOM_HEAD_2	'R'

/* Send signed data to ble device */
#define S_MSG_CMD_BLE_SENDSIGNED_HEAD_1	'S'
#define S_MSG_CMD_BLE_SENDSIGNED_HEAD_2	'S'

///////////////////////////////////////////////////////////////////

static s_lock_msg_type s_lock_msg_check_type(unsigned char *data, \
										unsigned short *length)
{
	s_lock_msg_type msg_type = unknown;
	
	//Remote controller
	if(S_MSG_RM_HEAD_1 == data[0] && \
		S_MSG_RM_HEAD_2 == data[1])
	{
		msg_type = ble_remotecontroller;
	}

	switch(msg_type)
	{
		case ble_remotecontroller:
			memcpy(&data[0], &data[2], *length - \
				S_MSG_HEAD_LENGTH);
			*length -= S_MSG_HEAD_LENGTH;
			break;

		default:
			break;
	}
	return msg_type;
}

static signed char s_uart_msg_remotectl_handle(\
						unsigned char *data, \
						unsigned short length)
{
	printf("s_uart_msg_remotectl_handle\r\n");
	debug_hex(data, length);

	if(S_MSG_CMD_BLE_CNRANDOM_HEAD_1 == data[0] && \
		S_MSG_CMD_BLE_CNRANDOM_HEAD_2 == data[1])
	{
		printf("S_MSG_CMD_BLE_CNRANDOM\r\n");

		S_OpenDoor_Connect_Search();
	}
	else if(S_MSG_CMD_BLE_SENDSIGNED_HEAD_1 == data[0] && \
		S_MSG_CMD_BLE_SENDSIGNED_HEAD_1 == data[1])
	{
		printf("S_MSG_CMD_BLE_SENDSIGNED\r\n");

		// S_OpenDoor_Connect_Search();
		S_OpenDoor_SendCheckSignedData(&data[2], length - 2);
	}

	return 0;
}
signed char S_Uart_Msg_Handle(const unsigned char *data, \
								unsigned short length)
{
	// printf("Get uart data\r\n");
	// debug_hex(data, length);

	s_lock_msg_type msg_type = s_lock_msg_check_type(data, \
												&length);

	switch(msg_type)
	{
		case ble_remotecontroller:
			s_uart_msg_remotectl_handle(data, length);
			break;

		default:
			//Shouldn't get here
			break;
	}

	H_CC2640R2F_UART_RxEnable();

	return 0;
}
